package com.sevenyear.excelanalyze.listener.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sevenyear.excelanalyze.common.utils.CalculateUtils;
import com.sevenyear.excelanalyze.entity.ChannelIrrigationFieldRate;
import com.sevenyear.excelanalyze.entity.PartitionBaseInfo;
import com.sevenyear.excelanalyze.entity.RainfallInfiltrationRate;
import com.sevenyear.excelanalyze.service.ChannelIrrigationFieldRateService;
import com.sevenyear.excelanalyze.service.PartitionBaseInfoService;

/**
 * @author ：SevenYear
 * @description：TODO
 * @date ：2021/8/29 23:05
 */
public class ChannelIrrigationFieldRateListener extends AnalysisEventListener<ChannelIrrigationFieldRate> {

    private ChannelIrrigationFieldRateService channelIrrigationFieldRateService;
    private PartitionBaseInfoService partitionBaseInfoService;

    public ChannelIrrigationFieldRateListener() {
    }

    public ChannelIrrigationFieldRateListener(ChannelIrrigationFieldRateService channelIrrigationFieldRateService, PartitionBaseInfoService partitionBaseInfoService) {
        this.channelIrrigationFieldRateService = channelIrrigationFieldRateService;
        this.partitionBaseInfoService = partitionBaseInfoService;
    }

    @Override
    public void invoke(ChannelIrrigationFieldRate channelIrrigationFieldRate, AnalysisContext analysisContext) {
        //计算平均值
        float average = CalculateUtils.average(channelIrrigationFieldRate.getChannelIrrigationFieldRateMin(), channelIrrigationFieldRate.getChannelIrrigationFieldRateMax());
        channelIrrigationFieldRate.setChannelIrrigationFieldRateAvg(average);
        //设置分区主键id,分区编码partitionCode,区域编码areaCode
        QueryWrapper<PartitionBaseInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("landform",channelIrrigationFieldRate.getLandform()).eq("clay_thickness",channelIrrigationFieldRate.getClayThickness());
        PartitionBaseInfo partitionBaseInfo = partitionBaseInfoService.getOne(wrapper);
        channelIrrigationFieldRate.setPartitionId(partitionBaseInfo.getId());
        channelIrrigationFieldRate.setPartitionCode(partitionBaseInfo.getPartitionCode());
        channelIrrigationFieldRate.setAreaCode(channelIrrigationFieldRate.getArea()+channelIrrigationFieldRate.getPartitionCode());
        UpdateWrapper<ChannelIrrigationFieldRate> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("area_code",channelIrrigationFieldRate.getAreaCode());
        channelIrrigationFieldRateService.saveOrUpdate(channelIrrigationFieldRate,updateWrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
